package me.frank.security.web;

import lombok.extern.slf4j.Slf4j;
import me.frank.security.validate.code.ImageValidateCode;
import me.frank.security.validate.code.ImageCodeGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @Author Frank Wang
 * @Description:
 * @Date 2018/12/12 9:40
 */
@Slf4j
@RestController
public class ValidateCodeController {

    public static final String SESSION_KEY="SESSION_KEY_IMAGE_CODE";

    @Autowired
    private ImageCodeGenerator imageCodeGenerator;

    @GetMapping("/code/image")
    public void createImageValidateCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        
        ImageValidateCode imageValidateCode =createImageCode();
        request.getSession().setAttribute(SESSION_KEY, imageValidateCode);
        ImageIO.write(imageValidateCode.getImage(),"JPEG",response.getOutputStream());

    }

    private ImageValidateCode createImageCode() {

        imageCodeGenerator.createCode();
        BufferedImage buffImg = imageCodeGenerator.getBuffImg();
        String code = imageCodeGenerator.getCode();
        ImageValidateCode imageValidateCode =new ImageValidateCode(buffImg,code,60);
        log.info("创建验证码成功：{}",code);
        return imageValidateCode;
    }
}
